from utils import excel_util, date_util


# 汇总操作结果
def deal_excel_result(data):
    content = data['content']
    size = len(content)
    content_beg = content[1]
    content_end = content[size - 1]
    end_price = content_end[3]
    beg_price = content_beg[3]
    end_capital = content_end[7]
    beg_date = content_beg[2]
    end_date = content_end[2]
    days = date_util.diff_days_str(content_beg[2], content_end[2])  # 总操作天数
    amt_incr = round((end_price - beg_price) / beg_price * 100, 2)  # 价格涨幅( %)    91.56
    earnings_incr = round((end_capital - 1000000) / 10000, 2)  # 盈利涨幅( %)    91.56
    days_hold_all = 0  # 持仓天数
    days_hold_all_flag = 0  # 持仓天数
    days_empty = 0
    days_empty_flag = 0
    for i in range(1, size):
        row = content[i]
        price = row[3]
        bs = row[4]
        hand = row[5]
        half = row[6]
        all = row[7]
        if days_empty_flag == 1:
            days_empty += row[9]
            days_empty_flag = 0
        if days_hold_all_flag == 1:
            days_hold_all += row[9]
            days_hold_all_flag = 0
        if bs == -1 and hand == 0:
            days_empty_flag = 1
        if bs == 1 and (all - half) / price / 100 < hand / 4:
            days_hold_all_flag = 1
    # content_arr = [['编码', '名称', '日期', '成交价', '买卖', '持有股', '持仓资金', '总资本', 'macd', '间隔天数']]
    content[0] = ['编码', '名称', '日期', '成交价', '买卖', '持有股', '持仓资金', '总资本', 'macd', '间隔天数', '等级', '评分','备注']  # 填充标题行
    content.append([])
    content.append(['', '', '', '名称', data['name']])
    content.append(['', '', '', '总操作天数', days])
    content.append(['', '', '', '开始日期', beg_date])
    content.append(['', '', '', '结束日期', end_date])
    content.append(['', '', '', '全仓天数', days_hold_all])
    content.append(['', '', '', '半仓天数', days - days_empty - days_hold_all])
    content.append(['', '', '', '空仓天数', days_empty])
    content.append(['', '', '', '价格涨幅( %)', amt_incr])
    content.append(['', '', '', '盈利涨幅( %)', earnings_incr])
    content.append(['', '', '', '操作次数', size - 1])
    return data


# 格式化成excel数据
def trans_excel_format(data):
    rq = data['rq']
    code = data['code']
    if 'bs' not in data.keys() or data['bs'] == 0:
        print(code + '当天无交易' + rq)
        return data
    rq = data['rq']
    content = data['content']
    # content_arr = [['编码', '名称', '日期', '成交价', '买卖', '持有股', '持仓资金', '总资本', 'macd', '间隔天数','等级','备注','评分']]
    # 距离上次交易间隔天数
    interval_days = 0
    if len(content) != 1:
        interval_days = date_util.diff_days_str(content[len(content) - 1][2], rq)
    row = [data['code'], data['name'], rq, data['rt_price'], data['bs'], data['hand'], data['position'],
           data['capital'] + data['position'], data['macd'], interval_days, data['score_info']['level'],
           data['score_info']['score'],data['score_info']['msg']]
    data['content'].append(row)
    return data
